package com.primb.bench.project.home.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.primb.baselibs.util.NetworkUtils;
import com.primb.baselibs.view.AutoToolbar;
import com.primb.bench.R;
import com.primb.bench.base.SwipeBaseActivity;
import com.primb.bench.common.constant.AppConstant;
import com.primb.bench.common.module.repository.LoanClientRepository;
import com.primb.bench.common.override.HttpSubscriber;
import com.primb.bench.project.home.entity.ClientInfoEntity;
import com.primb.bench.project.home.entity.RequestClientEntity;
import com.primb.netlibs.exception.ApiException;
import com.suke.widget.SwitchButton;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/**
 *
 * @author Chen
 * @date 2017/5/4
 * 功能描述：
 */

public class LoanClientActivity extends SwipeBaseActivity {

    @BindView(R.id.title_bar)
    TextView titleBar;
    @BindView(R.id.tool_bar)
    AutoToolbar toolBar;
    @BindView(R.id.recycler_add_info)
    RecyclerView recyclerAddInfo;
    @BindView(R.id.iv_top)
    ImageView ivTop;
    @BindView(R.id.et_loan_client_name)
    EditText etLoanClientName;
    @BindView(R.id.et_loan_client_number)
    EditText etLoanClientNumber;
    @BindView(R.id.swipe_content)
    SwipeRefreshLayout swipeContent;
    private Intent intent;
    private BaseQuickAdapter<ClientInfoEntity, BaseViewHolder> quickAdapter;
    private CompositeSubscription subscription;
    private RequestClientEntity requestClientEntity;
    private ClientInfoEntity info;

    @Override
    protected void onBaseIntent() {
        super.onBaseIntent();
        intent = getIntent();
        info = ((ClientInfoEntity) intent.getParcelableExtra("info"));
    }

    @Override
    protected int onBaseLayoutId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_loan_client;
    }

    @Override
    protected void onBaseBindView() {
        titleBar.setText("选择客户");
        ivTop.setVisibility(View.GONE);
        ivTop.setImageResource(R.mipmap.client_top_icon);
        toolBar.setNavigationOnClickListener(v -> LoanClientActivity.this.finish());
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerAddInfo.setLayoutManager(layoutManager);
        recyclerAddInfo.setHasFixedSize(true);
        quickAdapter = new BaseQuickAdapter<ClientInfoEntity, BaseViewHolder>(R.layout.item_client_info, null) {

            @Override
            protected void convert(BaseViewHolder helper, ClientInfoEntity item) {
                helper.setText(R.id.tv_item_client_name, item.getCustomerName());
                helper.setText(R.id.tv_item_client_number, item.getCustomerNum());
                helper.setText(R.id.tv_item_client_size, item.getCustomerSize());
                helper.setText(R.id.tv_item_client_type, item.getCustomerType());
                helper.setText(R.id.tv_item_client_credit, item.getCustomerCredit());
                helper.setText(R.id.tv_item_client_all_contribution, item.getCustomerAllContribution());
                helper.setText(R.id.tv_item_client_used_contribution, item.getCustomerUsedContribution());
                helper.setText(R.id.tv_item_client_contribution_point, item.getCustomerContributionNum());
                helper.setText(R.id.tv_item_client_all_profit, item.getCustomerAllProfit());
                helper.setText(R.id.tv_item_client_adjust_rate, item.getCustomerAdjustRate());
                SwitchButton switchButton = (SwitchButton) helper.getView(R.id.sw_item_client_is_contribution);
                switchButton.setOnTouchListener((v, event) -> {
                    Float point = Float.valueOf(item.getCustomerContributionNum());
                    if (point < 1 && event.getAction() == MotionEvent.ACTION_DOWN) {
                        showToast("剩余贡献点不足");
                        return true;
                    }
                    return false;
                });
                switchButton.setOnCheckedChangeListener((view, isChecked) -> {
                    item.setCustomerIsContribution(isChecked ? "1" : "0");
                });
                helper.addOnClickListener(R.id.sw_item_client_is_contribution);
                RelativeLayout layout = helper.getView(R.id.layout_parent_contribution);
                layout.setVisibility("0".equals(item.getCustomerContributionNumM()) ? View.GONE : View.VISIBLE);
                SwitchButton switchParent = (SwitchButton) helper.getView(R.id.switch_item_client_parent_contribution);
                switchParent.setOnTouchListener((v, event) -> {
                    Float point = Float.valueOf(item.getCustomerContributionNumM());
                    if (point < 1 && event.getAction() == MotionEvent.ACTION_DOWN) {
                        showToast("母公司剩余贡献点不足");
                        return true;
                    }
                    return false;
                });
                switchParent.setOnCheckedChangeListener((view, isChecked) -> item.setCustomerIsContributionM(isChecked ? "1" : "0"));
            }
        };
        quickAdapter.setOnLoadMoreListener(() -> {
            if (!NetworkUtils.isNetworkConnected(this)) {
                showToast("无网络连接，请连接网络后重试");
                quickAdapter.loadMoreFail();
                return;
            }
            if (quickAdapter.getData().size() >= 20) {
                loadMoreList();
            } else {
                quickAdapter.loadMoreEnd();
            }
        }, recyclerAddInfo);
        quickAdapter.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent();
            ClientInfoEntity infoEntity = (ClientInfoEntity) adapter.getData().get(position);
            intent.putExtra("info", infoEntity);
            LoanClientActivity.this.setResult(AppConstant.LOAN_CUSTOMER_RESULT, intent);
            LoanClientActivity.this.finish();
        });
        View layoutEmpty = getLayoutInflater().inflate(R.layout.empty_list_view, (ViewGroup) recyclerAddInfo.getParent(), false);
        quickAdapter.setEmptyView(layoutEmpty);
        recyclerAddInfo.setAdapter(quickAdapter);
        swipeContent.setColorSchemeColors(ContextCompat.getColor(this, android.R.color.holo_blue_bright), ContextCompat.getColor(this, android.R.color.holo_green_light),
                ContextCompat.getColor(this, android.R.color.holo_orange_light), ContextCompat.getColor(this, android.R.color.holo_red_light));
        swipeContent.setRefreshing(false);
        swipeContent.setOnRefreshListener(() -> {
            if (!NetworkUtils.isNetworkConnected(this)) {
                showToast("无网络连接，请连接网络后重试");
                swipeContent.setRefreshing(false);
                return;
            }
            requestClientEntity.rePage();
            getClientList();
        });
        etLoanClientNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                requestClientEntity.setCustId(s.toString());
            }
        });

        etLoanClientName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                requestClientEntity.setCustName(s.toString());
            }
        });
    }

    private void loadMoreList() {
        requestClientEntity.setPageAdd();
        Subscription subscribe = LoanClientRepository.getLoanClientListEntity(requestClientEntity).subscribe(new HttpSubscriber<List<ClientInfoEntity>>(this) {
            @Override
            public void onError(ApiException e) {
                showToast(e.getMessage());
                quickAdapter.loadMoreFail();
                requestClientEntity.setPageReduce();
            }

            @Override
            public void onCompleted() {
            }

            @Override
            public void onNext(List<ClientInfoEntity> clientInfoEntities) {
                if (clientInfoEntities.size() == 0) {
                    quickAdapter.loadMoreEnd();
                } else {
                    quickAdapter.addData(clientInfoEntities);
                    quickAdapter.notifyDataSetChanged();
                    quickAdapter.loadMoreComplete();
                }
            }
        });
        subscription.add(subscribe);
    }

    @Override
    protected void onLoadData() {
        subscription = new CompositeSubscription();
        requestClientEntity = new RequestClientEntity();
        if (info != null) {
            requestClientEntity.setCustId(info.getCustomerNum());
            getClientList();
        }
    }

    private void getClientList() {
        showLoadingDialog("加载中");
        Subscription subscribe = LoanClientRepository.getLoanClientListEntity(requestClientEntity)
                .subscribe(new HttpSubscriber<List<ClientInfoEntity>>(this) {
                    @Override
                    public void onError(ApiException e) {
                        swipeContent.setRefreshing(false);
                        quickAdapter.getData().clear();
                        quickAdapter.notifyDataSetChanged();
                        hideLoadingDialog();
                        showToast(e.getMessage());

                    }

                    @Override
                    public void onCompleted() {
                        swipeContent.setRefreshing(false);
                        hideLoadingDialog();
                    }

                    @Override
                    public void onNext(List<ClientInfoEntity> clientInfoEntities) {
                        if (clientInfoEntities.size() == 0) {
                            showAlterDialogOne("提示", "未查询到符合条件客户！");
                        } else {
                            quickAdapter.setNewData(clientInfoEntities);
                        }
                    }
                });
        subscription.add(subscribe);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppConstant.LOAN_CUSTOMER_REQUEST && resultCode == AppConstant.LOAN_CUSTOMER_REQUEST) {
            quickAdapter.getData().add(0, data.getParcelableExtra("info"));
            quickAdapter.notifyDataSetChanged();
        }
    }

    @OnClick({R.id.iv_top, R.id.et_loan_client_reset, R.id.et_loan_client_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_loan_client_reset:
                etLoanClientName.setText("");
                etLoanClientNumber.setText("");
                requestClientEntity.reSet();
                quickAdapter.getData().clear();
                quickAdapter.notifyDataSetChanged();
                break;
            case R.id.et_loan_client_search:
                recyclerAddInfo.requestFocus();
//                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); //得到InputMethodManager的实例
//                if (imm.isActive()) {//如果开启
//                    imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);//关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
//                }
                requestClientEntity.reSet();
                if (!TextUtils.isEmpty(etLoanClientNumber.getText().toString())) {
                    requestClientEntity.setCustId(etLoanClientNumber.getText().toString());
                }
                if (!TextUtils.isEmpty(etLoanClientName.getText().toString())) {
                    requestClientEntity.setCustName(etLoanClientName.getText().toString());
                }
                getClientList();
                break;
            case R.id.iv_top:
                Intent intent = new Intent(LoanClientActivity.this, AddInfoActivity.class);
                intent.putExtra("code", AppConstant.LOAN_CUSTOMER_REQUEST);
                startActivityForResult(intent, AppConstant.LOAN_CUSTOMER_REQUEST);
                break;
                default:
        }
    }
}
